package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
@Slf4j
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 根据用户id 或 设备id查询对应的行为实体 (优先使用userId)
     *
     * @param userId      用户id
     * @param equipmentId 设备id
     * @return
     */
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        if (userId != null) {
            //根据用户id查询
            ApBehaviorEntry entry = mongoTemplate.findOne(Query.query(Criteria.where("refId")
                            .is(userId).and("type").is(ApBehaviorEntry.Type.USER.getCode())),
                    ApBehaviorEntry.class);
            if (entry == null) {
                //创建实体
                entry = ApBehaviorEntry.builder().refId(userId)
                        .type(ApBehaviorEntry.Type.USER.getCode())
                        .createdTime(new Date()).build();
                mongoTemplate.save(entry);
            }
            return entry;
        }
        if (equipmentId != null) {
            //使用设备id查询
            ApBehaviorEntry entry = mongoTemplate.findOne(Query.query(Criteria.where("refId")
                            .is(equipmentId).and("type").is(ApBehaviorEntry.Type.EQUIPMENT.getCode())),
                    ApBehaviorEntry.class);
            if (entry == null) {
                //创建实体
                entry = ApBehaviorEntry.builder().refId(equipmentId)
                        .type(ApBehaviorEntry.Type.EQUIPMENT.getCode())
                        .createdTime(new Date()).build();
                mongoTemplate.save(entry);
            }
            return entry;
        }
        return null;
    }
}